package com.ccit.zhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccit.zhxy.pojo.Admin;
import com.ccit.zhxy.pojo.LoginForm;
import com.ccit.zhxy.pojo.Student;
import com.ccit.zhxy.pojo.Teacher;
import com.ccit.zhxy.service.AdminService;
import com.ccit.zhxy.service.StudentService;
import com.ccit.zhxy.service.TeacherService;
import com.ccit.zhxy.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 鹏少
 * @Date 2023/12/26
 * @Date 14:14
 */
@RestController
@RequestMapping("/sms/system")
@Slf4j
@Api(tags = "系统控制器")
public class SystemController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;


    @ApiOperation("登录请求验证")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request) {

        //验证码校验
        String verifiCode = (String) request.getSession().getAttribute("verifiCode");
        String loginFormVerifiCode = loginForm.getVerifiCode();
        if (loginFormVerifiCode == null || "".equals(verifiCode)) {
            return Result.fail().message("验证码失效，请刷新后重试");
        }
        if (!verifiCode.equalsIgnoreCase(loginFormVerifiCode)) {
            return Result.fail().message("验证码错误,请重新输入");
        }
        request.getSession().removeAttribute("verifiCode");

        //用户类型判断
        Map<String, String> map = new HashMap<>();
        Integer userType = loginForm.getUserType();

        switch (userType) {

            case 1:
                try {
                    Admin admin = adminService.lambdaQuery().eq(Admin::getName, loginForm.getUsername())
                            .eq(Admin::getPassword, MD5.encrypt(loginForm.getPassword())).one();
                    if (admin != null) {

                        String token = JwtHelper.createToken(admin.getId().longValue(), userType);
                        map.put("token", token);

                    } else {
                       throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);

                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                try {
                    Student student = studentService.lambdaQuery().eq(Student::getName, loginForm.getUsername())
                            .eq(Student::getPassword, MD5.encrypt(loginForm.getPassword())).one();
                    if (student != null) {

                        String token = JwtHelper.createToken(student.getId().longValue(), userType);
                        map.put("token", token);

                    } else {
                        throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);

                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                try {
                    Teacher teacher = teacherService.lambdaQuery().eq(Teacher::getName, loginForm.getUsername())
                            .eq(Teacher::getPassword, MD5.encrypt(loginForm.getPassword())).one();
                    if (teacher != null) {

                        String token = JwtHelper.createToken(teacher.getId().longValue(), userType);
                        map.put("token", token);

                    } else {
                        throw new RuntimeException("用户名或密码有误");
                    }
                    return Result.ok(map);

                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }



        }

        return Result.ok();


    }

    @ApiOperation("通过token获取用户信息")
    @GetMapping("getInfo")
    public Result getInfo(@RequestHeader("token") String token){

        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        Long userId = JwtHelper.getUserId(token);
        String userName = JwtHelper.getUserName(token);
        Integer userType = JwtHelper.getUserType(token);
        Map<String ,Object> map=new HashMap<>();
        switch (userType){

            case 1:
                Admin admin = adminService.lambdaQuery().eq(Admin::getId, userId).one();
                map.put("userType",userType);
                map.put("user",admin);
                break;

            case 2:
                Student student = studentService.lambdaQuery().eq(Student::getId, userId).one();
                map.put("userType",userType);
                map.put("user",student);
                break;

            case 3:
                Teacher teacher = teacherService.lambdaQuery().eq(Teacher::getId, userId).one();
                map.put("userType",userType);
                map.put("user",teacher);
                break;

        }
        return Result.ok(map);


    }


    @ApiOperation("获取验证码图片")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response) {

        log.info("生成验证码图片{}", LocalDateTime.now());
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode", verifiCode);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(verifiCodeImage, "JPEG", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @ApiOperation("图片的上传")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload( @ApiParam("文件二进制数据") @RequestParam MultipartFile multipartFile) throws IOException {

        String uuid = UUID.randomUUID().toString().toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        log.info("截取的类型{}",substring);
        String newName=uuid+substring;
        log.info("新的名字{}",newName);
        File file=new File("D:\\java\\zhxy\\target\\classes\\public\\upload\\"+newName);
        multipartFile.transferTo(file);
        String path="upload/"+newName;
        log.info("截取的类型{}",path);
        return Result.ok(path);


    }



    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(@RequestHeader("token") String token,
                            @PathVariable("oldPwd") String oldPwd,
                            @PathVariable("newPwd") String newPwd){
        boolean yOn = JwtHelper.isExpiration(token);
        if(yOn){
            //token过期
            return Result.fail().message("token失效!");
        }
        //通过token获取当前登录的用户id
        Long userId = JwtHelper.getUserId(token);
        //通过token获取当前登录的用户类型
        Integer userType = JwtHelper.getUserType(token);
        // 将明文密码转换为暗文
        oldPwd=MD5.encrypt(oldPwd);
        newPwd= MD5.encrypt(newPwd);
        if(userType == 1){
            QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Admin admin = adminService.getOne(queryWrapper);
            if (null!=admin) {
                admin.setPassword(newPwd);
                adminService.saveOrUpdate(admin);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }else if(userType == 2){
            QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Student student = studentService.getOne(queryWrapper);
            if (null!=student) {
                student.setPassword(newPwd);
                studentService.saveOrUpdate(student);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }
        else if(userType == 3){
            QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",userId.intValue()).eq("password",oldPwd);
            Teacher teacher = teacherService.getOne(queryWrapper);
            if (null!=teacher) {
                teacher.setPassword(newPwd);
                teacherService.saveOrUpdate(teacher);
            }else{
                return Result.fail().message("原密码输入有误！");
            }
        }
        return Result.ok();
    }
}
